package com.qyhl.module_activities.act.detail;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.ContextCompat;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.flyco.tablayout.SlidingTabLayout;
import com.google.android.material.appbar.AppBarLayout;
import com.gyf.immersionbar.ImmersionBar;
import com.qyhl.module_activities.R;
import com.qyhl.module_activities.R2;
import com.qyhl.module_activities.common.ActivityConstant;
import com.qyhl.module_activities.utils.view.InputLayout;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.ContextUtilts;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.constant.ErrorCode;
import com.qyhl.webtv.commonlib.entity.act.ActDetailsBean;
import com.qyhl.webtv.commonlib.entity.act.ActivityBean;
import com.qyhl.webtv.commonlib.entity.act.ActivityListTempBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.MShareBoard;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.config.HomeThemeColorUtil;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.umeng.socialize.UMShareAPI;
import com.weavey.loading.lib.LoadingLayout;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Field;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;
import es.dmoral.toasty.Toasty;

/**
 * 活动详情
 */
@Route(path = ARouterPathConstant.ACT_DETAILS)
public class ActivityNewDetailActivity extends BaseActivity implements ActNewDetailsContract.ActDetailsView,
        InputLayout.InputListener, BaseActivity.InputListener {
    @BindView(R2.id.tabLayout)
    SlidingTabLayout tabLayout;
    @BindView(R2.id.load_mask)
    LoadingLayout mActDetailsLoading;
    @BindView(R2.id.viewPager)
    ViewPager viewPager;
    @BindView(R2.id.act_name)
    TextView act_name;
    @BindView(R2.id.comment_num)
    TextView comment_num;
    @BindView(R2.id.collection_num)
    TextView collection_num;
    @BindView(R2.id.live_name)
    TextView live_name;
    @BindView(R2.id.signup_time)
    TextView signup_time;
    @BindView(R2.id.interest_num)
    TextView interest_num;
    @BindView(R2.id.app_bar)
    AppBarLayout app_bar;
    @BindView(R2.id.vote_time)
    TextView vote_time;
    @BindView(R2.id.vote_address)
    TextView vote_address;
    @BindView(R2.id.activity_time)
    TextView activity_time;
    @BindView(R2.id.vote_status)
    TextView vote_status;
    @BindView(R2.id.vote_max)
    TextView vote_max;
    @BindView(R2.id.act_cover)
    ImageView act_cover;
    @BindView(R2.id.colleciton)
    ImageView colleciton;
    @BindView(R2.id.actlivelayout)
    RelativeLayout actlivelayout;
    @BindView(R2.id.applylayout)
    RelativeLayout applylayout;
    @BindView(R2.id.tidbit)
    RelativeLayout tidbit;
    @BindView(R2.id.tidbittext)
    TextView tidbittext;
    @BindView(R2.id.live_cover)
    ImageView live_cover;
    @BindView(R2.id.inputlayout)
    InputLayout inputlayout;

    @Autowired(name = "actId")
    String actId;
    //当前vp所在位置
    private int nowVPposition = 0;

    private ActNewDetailsPresenter mPresenter;
    //登录标志
    private boolean isSignup = false;
    //局部刷新
    private boolean isLocal = false;
    //收藏状态
    private boolean isCollection = false;
    //收藏点击状态
    private boolean collectionEnable = true;

    private ActDetailsBean detailsBean;
    private ActNewDetailsPresenter.ViewPageAdapter adapter;
    private ActivityListTempBean activityTempBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }


    @Override
    protected int getContentView() {
        return R.layout.act_activity_newdetail;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter = new ActNewDetailsPresenter(this);
        BusFactory.getBus().register(this);
        initView();
    }

    @Override
    protected void setListener() {

    }

    private void initView() {

        addInputListener(this);
        inputlayout.setActivity(this);
        inputlayout.setInputListener(this);
        mActDetailsLoading.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View view) {
                getData();
            }
        });
        getData();
    }

    @OnClick({R2.id.back, R2.id.share, R2.id.colleciton})
    public void onClick(View view) {
        int i = view.getId();
        if (i == R.id.back) {
            finish();

        } else if (i == R.id.share) {
            if (detailsBean != null) {
                MShareBoard shareBoard = new MShareBoard(ActivityNewDetailActivity.this, String.valueOf(
                        detailsBean.getActivity().getActivity().getId()), detailsBean.getActivity().getActivity().getActName(), detailsBean.getActivity().getActivity().getPosterUrl(), detailsBean.getActivity().getActivity().getDigest(), CommonUtils.getInstance().getBannerId(), 19);
                shareBoard.showPopupWindow();
            }

        } else if (i == R.id.colleciton) {
            if (collectionEnable) {
                collectionEnable = false;
                CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                    @Override
                    public void login(boolean isLogin) {
                        if (isLogin) {
                            if (isCollection) {      //已经收藏
                                mPresenter.colleciton(Integer.parseInt(actId), "0");
                            } else {
                                mPresenter.colleciton(Integer.parseInt(actId), "1");
                            }
                        } else {
                            Toasty.normal(ActivityNewDetailActivity.this, "尚未登录或登录已失效！").show();
                            RouterManager.routerLogin(ActivityNewDetailActivity.this, 0);
                            collectionEnable = true;
                        }
                    }

                    @Override
                    public void error(String s) {
                        collectionEnable = true;
                    }
                });

            }

        } else {
        }
    }

    /**
     * 获取数据
     */
    public void getData() {
        mActDetailsLoading.setStatus(LoadingLayout.Loading);
        mPresenter.getData(Integer.parseInt(actId), 0);
    }


    @Override
    public void onError(int i, String message) {
        if (i == 1) {
            mActDetailsLoading.setErrorText(message);
            mActDetailsLoading.setReloadButtonText("点击重试");
            mActDetailsLoading.setErrorImage(R.drawable.error_content);
            mActDetailsLoading.setStatus(LoadingLayout.Error);
        } else if (i == 2) {
            mActDetailsLoading.setStatus(LoadingLayout.Success);
            Toasty.normal(this, message).show();
        }
    }

    @Override
    public void onSuccess(final ActDetailsBean data, CharSequence actname, ActNewDetailsPresenter.ViewPageAdapter adapter) {
        if (!this.isFinishing()) {
            detailsBean = data;
            this.adapter = adapter;
            activityTempBean = data.getActivity();
            if (data.getIsCollection() == 1) {
                isCollection = true;
                colleciton.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.active_nav_icon_collection_selected));
            }
            ActivityBean activityBean = activityTempBean.getActivity();
            //活动名称
            Glide.with(this).load(activityBean.getPosterUrl()).into(act_cover);
            act_name.setText(actname);
            activity_time.setText("活动时间: " + activityBean.getStartTime() + "-" + activityBean.getEndTime());
            if (activityTempBean.getVote() != null) {
                vote_time.setVisibility(View.VISIBLE);
                vote_time.setText("投票时间: " + activityTempBean.getVote().getStartTime() + "-" + activityTempBean.getVote().getEndTime());
            }

            if (!TextUtils.isEmpty(activityBean.getAddress())) {
                vote_address.setVisibility(View.VISIBLE);
                vote_address.setText("活动地址: " + activityBean.getAddress());
            }

            if (activityTempBean.getVote() != null && activityTempBean.getVote().getExtraRule() == 1) {
                if (activityBean.getIsVote() == 1) {
                    inputlayout.setVoteVisibility(true);
                    inputlayout.setNew(true);
                    if (activityTempBean.getVoteStatus() == ActivityConstant.VOTE_END || activityTempBean.getActStatus() == ActivityConstant.STATUS_END) {
                        inputlayout.setVoteEnable(0, "");
                    } else {
                        if (activityTempBean.getVoteStatus() == ActivityConstant.VOTE_OFF) {
                            inputlayout.setVoteEnable(2, "  " + DateUtils.getVoteTime(activityTempBean.getVote().getStartTime()) + " 投票  ");
                        } else {
                            inputlayout.setVoteEnable(1, "");
                        }

                    }
                } else {
                    inputlayout.setVoteVisibility(false);
                }
            }

            collection_num.setText(data.getSumCollection() + "人收藏");
            interest_num.setText(activityBean.getPageViews() + "人感兴趣");

            //活动直播
            if (data.getActivityLive() != null) {
                Glide.with(this).load(data.getActivityLive().getCoverPic()).into(live_cover);
                live_name.setText(data.getActivityLive().getTitle());
                actlivelayout.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle= new Bundle();
                        bundle.putString("id",data.getActivityLive().getId() + "");
                        RouterManager.router(ARouterPathConstant.TELE_VIDEO_ACTIVITY,bundle);
                    }
                });
            } else {
                actlivelayout.setVisibility(View.GONE);
            }

            //花絮
            if (data.getCatalog() != null) {
                tidbit.setVisibility(View.VISIBLE);
                tidbittext.setText(data.getCatalog().getName());
                tidbit.setOnClickListener(v -> {
                    Bundle bundle= new Bundle();
                    bundle.putString("id",data.getCatalog().getId());
                    bundle.putString("title", data.getCatalog().getName());
                    RouterManager.router(ARouterPathConstant.NEWS_LIST,bundle);
                });
            }

            //导航栏
            try {
                Class<? extends SlidingTabLayout> aClass = tabLayout.getClass();
                Field f = aClass.getDeclaredField("mTabPadding");
                f.setAccessible(true);
                f.set(tabLayout, StringUtils.dip2px(this, 15));
            } catch (Exception e) {
            }
            viewPager.setAdapter(adapter);
            tabLayout.setViewPager(viewPager);
            tabLayout.setTextSelectColor(HomeThemeColorUtil.getCheckColor());
            tabLayout.setTextUnselectColor(HomeThemeColorUtil.getTabNormalColor());
            tabLayout.getTitleView(0).getPaint().setFakeBoldText(true);
            viewPager.setCurrentItem(nowVPposition, false);

            //开启报名
            if (activityBean.getIsApply() == 1) {
                signup_time.setVisibility(View.VISIBLE);
                signup_time.setText("报名截止: " + activityBean.getApplyEndTime());

                int peopleNumber = activityBean.getPeopleNumber();
                if (peopleNumber == 0) {
                    vote_max.setText("报名限额: 不限");
                    vote_status.setVisibility(View.GONE);
                } else {
                    vote_max.setText("报名限额: " + peopleNumber);
                    if (activityBean.getIsExcess() == 0) {
                        //可以超额
                        vote_status.setVisibility(View.GONE);
                    } else {
                        if (data.getIsFull() == 0) {
                            vote_status.setText("尚有" + (peopleNumber - data.getSumPlayer()));
                        } else {
                            vote_status.setText("名额已满");
                        }
                    }
                }

                if (activityTempBean.getActStatus() == ActivityConstant.STATUS_PROCESSING) {
                    //是活动进行中才判断
                    if (activityTempBean.getApplyStatus() == ActivityConstant.SING_UP_ON) {
                        //是报名中,判断
                        checkSign();
                    } else if (activityTempBean.getApplyStatus() == ActivityConstant.SING_UP_OFF) {
                        //报名未开始
                        inputlayout.setSingUpEnable(activityTempBean.getApplyStatus(),
                                getTime(activityBean.getApplyStartTime()));
                        //隐藏余额
                        vote_status.setVisibility(View.GONE);
                    } else {
                        //报名已结束
                        checkSign();
                        //隐藏余额
                        vote_status.setVisibility(View.GONE);
                    }
                } else if (activityTempBean.getActStatus() == ActivityConstant.STATUS_END) {
                    inputlayout.setSingUpEnable(ActivityConstant.SING_UP_END);
                    //活动结束隐藏余额
                    vote_status.setVisibility(View.GONE);
                }
            } else {
                inputlayout.setSingUpVisibility(false);
                applylayout.setVisibility(View.GONE);
            }

            //开启评论
            if (activityBean.getIsComment() == 1) {
                inputlayout.setCommentVisibility();
                comment_num.setVisibility(View.VISIBLE);
                comment_num.setText(data.getCommentCount() + "人评论");
            } else {
                comment_num.setVisibility(View.GONE);
            }

            //同时没有开启评论和报名
            if (activityBean.getIsComment() != 1 && activityBean.getIsApply() != 1) {
                inputlayout.setVisibility(View.GONE);
            }
            mActDetailsLoading.setStatus(LoadingLayout.Success);
        }
    }

    //检查报名
    private void checkSign() {
        CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
            @Override
            public void login(boolean isLogin) {
                if (isLogin) {
                    mPresenter.checkSign(detailsBean.getActivity().getActivity().getId());
                } else {
                    //未登陆允许点击按钮
                    inputlayout.setSingUpEnable(-1);
                }
            }

            @Override
            public void error(String s) {
                //未登陆允许点击按钮
                inputlayout.setSingUpEnable(-1);
            }
        });

    }

    //判断报名未开始日期显示
    private String getTime(String applyStartTime) {
        String text = "报名未开始";
        SimpleDateFormat parse = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);

        try {
            Calendar date = Calendar.getInstance();
            Date datedate = parse.parse(applyStartTime);
            date.setTime(datedate);

            Calendar now = Calendar.getInstance();
            Date parsenow = new Date(System.currentTimeMillis());
            now.setTime(parsenow);

            if (now.get(Calendar.YEAR) == date.get(Calendar.YEAR)) {
                SimpleDateFormat format;
                if ((now.get(Calendar.DAY_OF_YEAR) - date.get(Calendar.DAY_OF_YEAR)) == 0) {
                    format = new SimpleDateFormat("HH:mm", Locale.US);
                } else {
                    format = new SimpleDateFormat("MM/dd", Locale.US);
                }
                text = format.format(datedate);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return "  " + text + " 开始  ";
    }

    @Override
    public void checkError(int code) {
        if (code == ErrorCode.PLAYER_FULL) {
            vote_status.setText("名额已满");
        }
        inputlayout.setSingUpEnable(code);
        dismissLoading();
    }

    @Override
    public void checkSuccess() {
        inputlayout.setSingUpEnable(-1);
        if (isSignup) {
            dismissLoading();
            Bundle bundle = new Bundle();
            bundle.putInt("actId", detailsBean.getActivity().getActivity().getId());
            bundle.putInt("IsAlbum", detailsBean.getActivity().getActivity().getIsAlbum());

            RouterManager.router(this,ARouterPathConstant.ACT_SIGN_UP,R.anim.open_up, R.anim.close_down,999,bundle);
            isSignup = false;
        }
    }

    @Override
    public void collecitonError(String msg) {
        collectionEnable = true;
    }

    @Override
    public void collecitonSuccess() {
        collectionEnable = true;
        isCollection = !isCollection;
        String nums = collection_num.getText().toString();
        int num = Integer.parseInt(nums.substring(0, nums.indexOf("人")));
        if (isCollection) {
            //收藏成功
            showToast("收藏成功", INFO);
            collection_num.setText(++num + "人收藏");
            colleciton.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.active_nav_icon_collection_selected));
        } else {
            //取消成功
            showToast("取消成功", INFO);
            collection_num.setText(--num + "人收藏");
            colleciton.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.active_nav_icon_collection));
        }
    }

    @Override
    public void singup() {
        if (inputlayout.getSingUpCode() == ActivityConstant.SING_UP_OFF ||
                inputlayout.getSingUpCode() == ErrorCode.JOIN_ACTIVITY_ERROR2) {
            showToast("报名将于" + detailsBean.getActivity().getActivity().getApplyStartTime() +
                    "分开始，敬请期待", INFO);
        } else {
            //报名点击
            showSimpleLoading();
            CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                @Override
                public void login(boolean isLogin) {
                    if (isLogin) {
                        isSignup = true;
                        mPresenter.checkSign(detailsBean.getActivity().getActivity().getId());
                    } else {
                        dismissLoading();
                        Toasty.normal(ActivityNewDetailActivity.this, "尚未登录或登录已失效！").show();
                        RouterManager.routerLogin(ActivityNewDetailActivity.this, 0);
                    }
                }

                @Override
                public void error(String s) {
                    dismissLoading();
                }
            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 999 && resultCode == 666) {
            inputlayout.setSingUpEnable(ErrorCode.SGIN_ACTIVITY_REVIEW);
            isLocal = true;
            mPresenter.getData(Integer.parseInt(actId), 0);
        }
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void send(String text) {
        viewPager.setCurrentItem(adapter.getCommentPosition(), false);
        if (!TextUtils.isEmpty(text) && !TextUtils.isEmpty(text.trim())) {
            BusFactory.getBus().post(new Event.ActivityEvent(text));
        } else {
            Toasty.normal(ActivityNewDetailActivity.this, "评论内容不能为空").show();
        }
    }

    @Override
    public void dovote() {
        viewPager.setCurrentItem(adapter.getPlayerListPosition(), false);
        if (activityTempBean == null) {
            showToast("出错啦", 4);
            return;
        }

        if (activityTempBean.getVote() != null && activityTempBean.getVoteStatus() == ActivityConstant.VOTE_OFF) {
            showToast("投票将于" + activityTempBean.getVote().getStartTime() + "开始，敬请期待！", 4);
        } else {
            CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                @Override
                public void login(boolean isLogin) {
                    if (isLogin) {
                        BusFactory.getBus().post(new Event.DoVote());
                    } else {
                        RouterManager.routerLogin(ActivityNewDetailActivity.this, 0);
                        Toasty.normal(ActivityNewDetailActivity.this, "尚未登录或登录已失效！", Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void error(String s) {

                }
            });
        }
    }

    @Override
    public void showkeyboard() {

    }

    @Override
    public void hideKeyboard() {
        if (inputlayout.getStatus() == InputLayout.STATUS_INPUT) {
            inputlayout.changeDefaultStatus();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMessage(Event.LoginMessage event) {
        nowVPposition = viewPager.getCurrentItem();
        if (event != null) {
            if (event.isLogin()) {
                //登录
                ContextUtilts.getInstance().setmContext(this);
                mPresenter.getData(Integer.parseInt(actId), 0);
            }
        }
    }

    @Override
    protected void onDestroy() {
        BusFactory.getBus().unregister(this);
        removeInputListener(this);
        super.onDestroy();
    }



    @Override
    protected void onResume() {
        super.onResume();
        ActionLogUtils.getInstance().onResume(this, ActionConstant.ACTIVITY_DETAIL);
    }

    @Override
    protected void onPause() {
        super.onPause();
        ActionLogUtils.getInstance().onPause(this, ActionConstant.ACTIVITY_DETAIL);
    }
}
